const Resource = require("../../model/resource.model");
const Classify = require("../../model/classify.model");
const Sequelize = require("sequelize");
class ResourceService {
  async getResource(args) {
    const { current = 1, pageSize = 10000, ...remainingParameters } = args;
    const offset = (current - 1) * pageSize;
    const whereOptions = {};
    if (remainingParameters.classify_id) {
      whereOptions.classify_id = {
        [Sequelize.Op.like]: `%${remainingParameters.classify_id}%`,
      };
    }
    if (remainingParameters.title) {
      whereOptions.title = {
        [Sequelize.Op.like]: `%${remainingParameters.title}%`,
      };
    }
    if (remainingParameters.description) {
      whereOptions.description = {
        [Sequelize.Op.like]: `%${remainingParameters.description}%`,
      };
    }
    const { rows: list, count: total } = await Resource.findAndCountAll({
      limit: Number(pageSize),
      offset: offset,
      where: whereOptions,
      include: [
        {
          model: Classify,
          as: "classifyInfo",
          attributes: ["id", "title"],
        },
      ],
      order: [["createdAt",'DESC']],
    });
    return {
      current,
      pageSize,
      total,
      list,
    };
  }
  async createResource(args) {
    const { id, createdAt, updatedAt, ...remainingParameters } = args;
    const resource = await Resource.create(remainingParameters);
    return resource;
  }
  async updateResource(args) {
    const { id, ...remainingParameters } = args;
    const resource = await Resource.update(
      {
        ...remainingParameters,
      },
      {
        where: {
          id,
        },
      }
    );
    return resource;
  }
  async deleteResource(args) {
    const { id } = args;
    const resource = await Resource.destroy({
      where: {
        id,
      },
    });
    return resource;
  }
}

module.exports = new ResourceService();
